package com.room.search.web.rest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.room.search.IntegrationTest;
import com.room.search.domain.RoomBroker;
import com.room.search.repository.RoomBrokerRepository;
import com.room.search.service.dto.RoomBrokerDTO;
import com.room.search.service.mapper.RoomBrokerMapper;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link RoomBrokerResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class RoomBrokerResourceIT {

    private static final String DEFAULT_NAME = "AAAAAAAAAA";
    private static final String UPDATED_NAME = "BBBBBBBBBB";

    private static final Integer DEFAULT_SERVER_AGE = 1;
    private static final Integer UPDATED_SERVER_AGE = 2;

    private static final Integer DEFAULT_TRADE_RECORD = 1;
    private static final Integer UPDATED_TRADE_RECORD = 2;

    private static final String DEFAULT_APPRAISE = "AAAAAAAAAA";
    private static final String UPDATED_APPRAISE = "BBBBBBBBBB";

    private static final String DEFAULT_CONTACT = "AAAAAAAAAA";
    private static final String UPDATED_CONTACT = "BBBBBBBBBB";

    private static final String DEFAULT_RATES = "AAAAAAAAAA";
    private static final String UPDATED_RATES = "BBBBBBBBBB";

    private static final String ENTITY_API_URL = "/api/room-brokers";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private RoomBrokerRepository roomBrokerRepository;

    @Autowired
    private RoomBrokerMapper roomBrokerMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restRoomBrokerMockMvc;

    private RoomBroker roomBroker;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static RoomBroker createEntity(EntityManager em) {
        RoomBroker roomBroker = new RoomBroker()
            .name(DEFAULT_NAME)
            .serverAge(DEFAULT_SERVER_AGE)
            .tradeRecord(DEFAULT_TRADE_RECORD)
            .appraise(DEFAULT_APPRAISE)
            .contact(DEFAULT_CONTACT)
            .rates(DEFAULT_RATES);
        return roomBroker;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static RoomBroker createUpdatedEntity(EntityManager em) {
        RoomBroker roomBroker = new RoomBroker()
            .name(UPDATED_NAME)
            .serverAge(UPDATED_SERVER_AGE)
            .tradeRecord(UPDATED_TRADE_RECORD)
            .appraise(UPDATED_APPRAISE)
            .contact(UPDATED_CONTACT)
            .rates(UPDATED_RATES);
        return roomBroker;
    }

    @BeforeEach
    public void initTest() {
        roomBroker = createEntity(em);
    }

    @Test
    @Transactional
    void createRoomBroker() throws Exception {
        int databaseSizeBeforeCreate = roomBrokerRepository.findAll().size();
        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);
        restRoomBrokerMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO)))
            .andExpect(status().isCreated());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeCreate + 1);
        RoomBroker testRoomBroker = roomBrokerList.get(roomBrokerList.size() - 1);
        assertThat(testRoomBroker.getName()).isEqualTo(DEFAULT_NAME);
        assertThat(testRoomBroker.getServerAge()).isEqualTo(DEFAULT_SERVER_AGE);
        assertThat(testRoomBroker.getTradeRecord()).isEqualTo(DEFAULT_TRADE_RECORD);
        assertThat(testRoomBroker.getAppraise()).isEqualTo(DEFAULT_APPRAISE);
        assertThat(testRoomBroker.getContact()).isEqualTo(DEFAULT_CONTACT);
        assertThat(testRoomBroker.getRates()).isEqualTo(DEFAULT_RATES);
    }

    @Test
    @Transactional
    void createRoomBrokerWithExistingId() throws Exception {
        // Create the RoomBroker with an existing ID
        roomBroker.setId(1L);
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        int databaseSizeBeforeCreate = roomBrokerRepository.findAll().size();

        // An entity with an existing ID cannot be created, so this API call must fail
        restRoomBrokerMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO)))
            .andExpect(status().isBadRequest());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void getAllRoomBrokers() throws Exception {
        // Initialize the database
        roomBrokerRepository.saveAndFlush(roomBroker);

        // Get all the roomBrokerList
        restRoomBrokerMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(roomBroker.getId().intValue())))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].serverAge").value(hasItem(DEFAULT_SERVER_AGE)))
            .andExpect(jsonPath("$.[*].tradeRecord").value(hasItem(DEFAULT_TRADE_RECORD)))
            .andExpect(jsonPath("$.[*].appraise").value(hasItem(DEFAULT_APPRAISE)))
            .andExpect(jsonPath("$.[*].contact").value(hasItem(DEFAULT_CONTACT)))
            .andExpect(jsonPath("$.[*].rates").value(hasItem(DEFAULT_RATES)));
    }

    @Test
    @Transactional
    void getRoomBroker() throws Exception {
        // Initialize the database
        roomBrokerRepository.saveAndFlush(roomBroker);

        // Get the roomBroker
        restRoomBrokerMockMvc
            .perform(get(ENTITY_API_URL_ID, roomBroker.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(roomBroker.getId().intValue()))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
            .andExpect(jsonPath("$.serverAge").value(DEFAULT_SERVER_AGE))
            .andExpect(jsonPath("$.tradeRecord").value(DEFAULT_TRADE_RECORD))
            .andExpect(jsonPath("$.appraise").value(DEFAULT_APPRAISE))
            .andExpect(jsonPath("$.contact").value(DEFAULT_CONTACT))
            .andExpect(jsonPath("$.rates").value(DEFAULT_RATES));
    }

    @Test
    @Transactional
    void getNonExistingRoomBroker() throws Exception {
        // Get the roomBroker
        restRoomBrokerMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putNewRoomBroker() throws Exception {
        // Initialize the database
        roomBrokerRepository.saveAndFlush(roomBroker);

        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();

        // Update the roomBroker
        RoomBroker updatedRoomBroker = roomBrokerRepository.findById(roomBroker.getId()).get();
        // Disconnect from session so that the updates on updatedRoomBroker are not directly saved in db
        em.detach(updatedRoomBroker);
        updatedRoomBroker
            .name(UPDATED_NAME)
            .serverAge(UPDATED_SERVER_AGE)
            .tradeRecord(UPDATED_TRADE_RECORD)
            .appraise(UPDATED_APPRAISE)
            .contact(UPDATED_CONTACT)
            .rates(UPDATED_RATES);
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(updatedRoomBroker);

        restRoomBrokerMockMvc
            .perform(
                put(ENTITY_API_URL_ID, roomBrokerDTO.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO))
            )
            .andExpect(status().isOk());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
        RoomBroker testRoomBroker = roomBrokerList.get(roomBrokerList.size() - 1);
        assertThat(testRoomBroker.getName()).isEqualTo(UPDATED_NAME);
        assertThat(testRoomBroker.getServerAge()).isEqualTo(UPDATED_SERVER_AGE);
        assertThat(testRoomBroker.getTradeRecord()).isEqualTo(UPDATED_TRADE_RECORD);
        assertThat(testRoomBroker.getAppraise()).isEqualTo(UPDATED_APPRAISE);
        assertThat(testRoomBroker.getContact()).isEqualTo(UPDATED_CONTACT);
        assertThat(testRoomBroker.getRates()).isEqualTo(UPDATED_RATES);
    }

    @Test
    @Transactional
    void putNonExistingRoomBroker() throws Exception {
        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();
        roomBroker.setId(count.incrementAndGet());

        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restRoomBrokerMockMvc
            .perform(
                put(ENTITY_API_URL_ID, roomBrokerDTO.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchRoomBroker() throws Exception {
        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();
        roomBroker.setId(count.incrementAndGet());

        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restRoomBrokerMockMvc
            .perform(
                put(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamRoomBroker() throws Exception {
        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();
        roomBroker.setId(count.incrementAndGet());

        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restRoomBrokerMockMvc
            .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO)))
            .andExpect(status().isMethodNotAllowed());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateRoomBrokerWithPatch() throws Exception {
        // Initialize the database
        roomBrokerRepository.saveAndFlush(roomBroker);

        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();

        // Update the roomBroker using partial update
        RoomBroker partialUpdatedRoomBroker = new RoomBroker();
        partialUpdatedRoomBroker.setId(roomBroker.getId());

        restRoomBrokerMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedRoomBroker.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedRoomBroker))
            )
            .andExpect(status().isOk());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
        RoomBroker testRoomBroker = roomBrokerList.get(roomBrokerList.size() - 1);
        assertThat(testRoomBroker.getName()).isEqualTo(DEFAULT_NAME);
        assertThat(testRoomBroker.getServerAge()).isEqualTo(DEFAULT_SERVER_AGE);
        assertThat(testRoomBroker.getTradeRecord()).isEqualTo(DEFAULT_TRADE_RECORD);
        assertThat(testRoomBroker.getAppraise()).isEqualTo(DEFAULT_APPRAISE);
        assertThat(testRoomBroker.getContact()).isEqualTo(DEFAULT_CONTACT);
        assertThat(testRoomBroker.getRates()).isEqualTo(DEFAULT_RATES);
    }

    @Test
    @Transactional
    void fullUpdateRoomBrokerWithPatch() throws Exception {
        // Initialize the database
        roomBrokerRepository.saveAndFlush(roomBroker);

        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();

        // Update the roomBroker using partial update
        RoomBroker partialUpdatedRoomBroker = new RoomBroker();
        partialUpdatedRoomBroker.setId(roomBroker.getId());

        partialUpdatedRoomBroker
            .name(UPDATED_NAME)
            .serverAge(UPDATED_SERVER_AGE)
            .tradeRecord(UPDATED_TRADE_RECORD)
            .appraise(UPDATED_APPRAISE)
            .contact(UPDATED_CONTACT)
            .rates(UPDATED_RATES);

        restRoomBrokerMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedRoomBroker.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedRoomBroker))
            )
            .andExpect(status().isOk());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
        RoomBroker testRoomBroker = roomBrokerList.get(roomBrokerList.size() - 1);
        assertThat(testRoomBroker.getName()).isEqualTo(UPDATED_NAME);
        assertThat(testRoomBroker.getServerAge()).isEqualTo(UPDATED_SERVER_AGE);
        assertThat(testRoomBroker.getTradeRecord()).isEqualTo(UPDATED_TRADE_RECORD);
        assertThat(testRoomBroker.getAppraise()).isEqualTo(UPDATED_APPRAISE);
        assertThat(testRoomBroker.getContact()).isEqualTo(UPDATED_CONTACT);
        assertThat(testRoomBroker.getRates()).isEqualTo(UPDATED_RATES);
    }

    @Test
    @Transactional
    void patchNonExistingRoomBroker() throws Exception {
        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();
        roomBroker.setId(count.incrementAndGet());

        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restRoomBrokerMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, roomBrokerDTO.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchRoomBroker() throws Exception {
        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();
        roomBroker.setId(count.incrementAndGet());

        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restRoomBrokerMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamRoomBroker() throws Exception {
        int databaseSizeBeforeUpdate = roomBrokerRepository.findAll().size();
        roomBroker.setId(count.incrementAndGet());

        // Create the RoomBroker
        RoomBrokerDTO roomBrokerDTO = roomBrokerMapper.toDto(roomBroker);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restRoomBrokerMockMvc
            .perform(
                patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(roomBrokerDTO))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the RoomBroker in the database
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteRoomBroker() throws Exception {
        // Initialize the database
        roomBrokerRepository.saveAndFlush(roomBroker);

        int databaseSizeBeforeDelete = roomBrokerRepository.findAll().size();

        // Delete the roomBroker
        restRoomBrokerMockMvc
            .perform(delete(ENTITY_API_URL_ID, roomBroker.getId()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<RoomBroker> roomBrokerList = roomBrokerRepository.findAll();
        assertThat(roomBrokerList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
